import { defineStore } from 'pinia'
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from '@/utils'
// import authMenuList from '@/assets/json/authMenuList.json'
import { getCurrentUserPath } from '@/api/modules/sys.js'
export const useAuthStore = defineStore({
  id: 'geeker-auth',
  state: () => ({
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: '',
    staticMenus: [
      {
        path: '/home',
        name: 'home',
        component: '/Home/index',
        meta: {
          icon: 'HomeFilled',
          title: '首页',
          isLink: '',
          isHide: false,
          isFull: false,
          isAffix: true,
          isKeepAlive: true
        }
      }
    ]
  }),
  getters: {
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // Get AuthMenuList
    async getAuthMenuList() {
      let menuList = []
      const deepMenList = datas => {
        let arr = []
        datas.forEach(({ compent, value, name, children, icoUrl, id }) => {
          const child = children ? deepMenList(children) : []
          const obj = {
            path: value,
            name: value?.split('/')[1],
            id: id,
            component: compent,
            meta: {
              icon: 'HomeFilled',
              icoUrl,
              title: name
            },
            children: child
          }
          value && arr.push(obj)
        })
        return arr
      }
      const { data } = await getCurrentUserPath().catch(() => {
        this.authMenuList = this.staticMenus
      })
      if (data) {
        menuList = deepMenList(data)
      }
      this.authMenuList = this.staticMenus.concat(menuList)
    },
    // Set RouteName
    async setRouteName(name) {
      this.routeName = name
    }
  }
})
